package com.lagou.order.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ配置类
 * @author yzh
 */
@Configuration
public class RabbitMQConfig {

    @Value("${rabbitmqconfig.exchange-name}")
    private String exchangeName;

    @Value("${rabbitmqconfig.exchange-dlx-name}")
    private String exchangeDlxName;

    @Value("${rabbitmqconfig.queue-name}")
    private String queueName;

    @Value("${rabbitmqconfig.queue-dlx-name}")
    private String queueDlxName;

    @Value("${rabbitmqconfig.routing-name}")
    private String routingName;

    @Value("${rabbitmqconfig.routing-dlx-name}")
    private String routingDlxName;

    @Value("${rabbitmqconfig.x-message-ttl}")
    private Integer xMessageTTL;

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange(exchangeName, true, false, null);
    }

    @Bean
    public DirectExchange exchangeDlx() {
        return new DirectExchange(exchangeDlxName, true, false, null);
    }

    @Bean
    public Queue queue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl", xMessageTTL);
        arguments.put("x-dead-letter-exchange", exchangeDlxName);
        arguments.put("x-dead-letter-routing-key", routingDlxName);
        return new Queue(queueName, true, false, false, arguments);
    }

    @Bean
    public Queue queueDlx() {
        return new Queue(queueDlxName, true, false, false, null);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(exchange()).with(routingName);
    }

    @Bean
    public Binding bindingDlx() {
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with(routingDlxName);
    }
}
